package com.director.core;

import com.director.core.annotation.PollingProviderConfig;
import com.director.core.json.JsonParser;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Author: Simone Ricciardi
 * Date: 8-giu-2010
 * Time: 12.04.33
 */
public class PollingProvider extends AbstractProvider {

   private static final long DEFAULT_INTERVAL = 3000;

   private long interval = DEFAULT_INTERVAL;
   private DirectAction directAction;
   private DirectMethod directMethod;

   protected PollingProvider(String id, String namespace, ProviderType type, DirectConfiguration configuration) {
      super(id, namespace, type, configuration);
   }

   public long getInterval() {
      return interval;
   }

   public DirectAction getDirectAction() {
      return directAction;
   }

   public DirectMethod getDirectMethod() {
      return directMethod;
   }

   @Override
   public void registerMethod(String actionName, String methodName, Class actionClass, Method method) {
      this.directAction = new DirectAction(this.getNamespace(), actionName, actionClass);
      this.directMethod = this.directAction.addMethod(methodName, method);
      if(method.isAnnotationPresent(PollingProviderConfig.class)) {
         PollingProviderConfig config = method.getAnnotation(PollingProviderConfig.class);
         this.interval = config.interval();
      }
   }

   @Override
   public boolean hasMethod(Method method, Class aClass) {
      return this.directAction.getActionClass().equals(aClass) && this.directAction.hasMethod(method);
   }

   @Override
   public void doProcess() throws Throwable {
      this.directMethod.invoke(null);
   }

   @Override
   public void formatForOutput() throws IOException {
      List<DirectEvent> events = DirectContext.get().getEvents();
      JsonParser jsonParser = DirectContext.get().getConfiguration().getParser();
      PrintWriter writer = DirectContext.get().getResponse().getWriter();
      jsonParser.format(events, writer);
   }
}
